package com.example.springboot.controller;

import cn.hutool.core.date.DateUtil;
import com.example.springboot.common.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;

import com.example.springboot.service.IQuestionService;
import com.example.springboot.entity.Question;

import org.springframework.web.bind.annotation.RestController;
/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wgc
 * @since 2023-10-02
 */
@RestController
@RequestMapping("/question")
        public class QuestionController {
    
    @Resource
    private IQuestionService questionService;

    //新增和修改
    @PostMapping
    public Result save(@RequestBody Question question) {  //@RequestBody接收前端数据
        if(question.getId() == null){
            question.setTime(DateUtil.now());
            question.setUserId(TokenUtils.getCurrentUser().getId());
        }
        questionService.saveOrUpdate(question);
        return Result.success();
    }

    //查询所有数据
    @GetMapping()
    public Result findAll() {
        return Result.success(questionService.list());
    }

    //删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
         return Result.success(questionService.removeById(id));
    }
    //批量删除
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(questionService.removeByIds(ids));
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(questionService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam(defaultValue = "") String name,
                           @RequestParam(required = false) Integer courseId,
                           @RequestParam(required = false) Integer type,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {

        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (!"".equals(name)) {
        queryWrapper.like("name", name);
        }
        if(courseId != null){
            queryWrapper.eq("course_id", courseId);
        }
        if(type != null){
            queryWrapper.eq("type", type);
        }
        return Result.success(questionService.page(new Page<>(pageNum, pageSize),queryWrapper));
        }
    }



